package com.easy.util;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;

@Slf4j
public class GitMyUtil {

    /**
     * 检查项目是否有更新代码
     *
     * @param localCodePath = "D:\\workspase\\dxhh_applet";
     *                      username = "1063097422@qq.com";
     *                      password = "LanYu@74123";
     * @return
     */
    public static boolean testCheck(String localCodePath, String username, String password) {
        boolean hasMore = false;
        try {
            File gitFile = new File(localCodePath + "/.git");
            if (!gitFile.exists()) {
                log.error("本地项目不存在：{}", gitFile.getAbsolutePath());
                return false;
            }
            // 打开本地代码的 Git 仓库
            Repository localRepo = new FileRepositoryBuilder()
                    .setGitDir(new File(localCodePath + "/.git"))
                    .build();
            // 拉取远程仓库的更新
            Git git = new Git(localRepo);
            hasMore = git.fetch()
                    .setRemote("origin")
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                    .call()
                    .getTrackingRefUpdates().size() > 0;
            git.close();
            localRepo.close();
        } catch (IOException | GitAPIException e) {
            log.error("检查代码更新失败：{}", e.getMessage());
        }
        return hasMore;
    }
}
